﻿using System;
using System.Web;

namespace Wiki.Web
{
    public static class IHttpRequestExtensionMethods
    {
        public static bool Accepts(this IHttpRequest arg, string type, string subtype)
        {
            return Accepts(arg, type, subtype, true);
        }

        public static bool Accepts(this IHttpRequest arg, string type, string subtype, bool any)
        {
            if (arg == null) throw new ArgumentNullException("arg");

            bool value = arg.Headers["Accept"].IsNullOrEmpty();

            if (!value)
            {
                foreach (string accept in arg.AcceptTypes)
                {
                    if (any && accept.Contains("*/*"))
                    {
                        value = true;
                        break;
                    }
                    else if (any && accept.Contains(type + "/*"))
                    {
                        value = true;
                        break;
                    }
                    else if (accept.Contains(String.Concat(type, "/", subtype)))
                    {
                        value = true;
                        break;
                    }
                }
            }

            return value;
        }

        public static bool IsSupportedMediaType(this IHttpRequest arg, string contentType)
        {
            bool value = false;

            if (!contentType.IsNullOrEmpty())
            {
                value = arg.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
            }

            return value;
        }

        public static bool IsHttpMethod(this IHttpRequest arg, params string[] methods)
        {
            bool value = false;

            if ((methods != null) && (methods.Length != 0))
            {
                foreach (string method in methods)
                {
                    if (arg.HttpMethod.Equals(method, StringComparison.OrdinalIgnoreCase))
                    {
                        value = true;
                        break;
                    }
                }
            }

            return value;
        }
    }
}